package com.caine.filter.config;

import com.caine.filter.filter.TokenVerifyFilter;
import com.caine.filter.handler.AuthAccessDeniedHandler;
import com.caine.filter.handler.AuthAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @Author: CaineZhu
 * @Description: 安全拦截配置
 * @Date: Created in 17:20 2021/1/7
 * @Modified By:
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   /* @Autowired
    private UserService userService;*/

    @Value("${com.caine.white-url:/access/token}")
    private String whiteUrl;

    @Resource
    private RsaKeyProperties prop;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //指定认证对象的来源
   /* public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }*/
    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers(whiteUrl.split(",")).permitAll()
                .anyRequest().authenticated().and()
                .addFilter(new TokenVerifyFilter(super.authenticationManager(), prop))
                .exceptionHandling()
                .authenticationEntryPoint(new AuthAuthenticationEntryPoint())
                .accessDeniedHandler(new AuthAccessDeniedHandler())
                .and()
//                .addFilter(new TokenLoginFilter(super.authenticationManager(), prop))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


}
